<template>
  <BasicModal
    :width="540"
    :minHeight="260"
    v-bind="$attrs"
    @register="register"
    title="退卡"
    :footer="null"
    :canFullscreen="false"
    :maskClosable="false"
    :centered="true"
    :destroyOnClose="true"
  >
    <div class="panel">
      <div>该订单包含{{ state.cardAllPack.length }}张卡，请选择要退的卡（单选）</div>

      <a-flex
        gap="middle"
        v-if="!!state.cardAllPack.length"
        style="height: 100%; margin-top: 12px"
        wrap="wrap"
      >
        <card-item :data-source="state.cardAllPack" @select="onSelect" :is-select="true" />
      </a-flex>
    </div>
  </BasicModal>

  <OrderRefund3 @register="registerRefund3" @complete="emit('complete')"/>
</template>
<script setup>
  /**
   * 选择退卡
   */

  import { reactive, ref, watch } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { POST } from '@/api/http.js';
  import { exist } from '@/api/util.js';
  import CardItem from './card-select-item.vue';
  import OrderRefund3 from './order-refund-3.vue';
  import { useDrawer } from '@/components/Drawer';

  const orderHeader = ref([]);
  const record = ref({});

  const emit = defineEmits(['complete']);
  const { createMessage } = useMessage();
  const [registerRefund3, { openDrawer: refundDrawer3 }] = useDrawer();

  const state = reactive({
    showInvalid: false,
    version: 0,
    cardAllPack: [],
  });

  watch(
    () => [state.showInvalid, state.version],
    () => {
      const { showInvalid, cardEffectivePack, cardInvalidPack } = state;
      state.cardAllPack = showInvalid
        ? [...cardEffectivePack, ...cardInvalidPack]
        : [...cardEffectivePack];
    },
  );

  const [register, { closeModal }] = useModalInner(
    async ({ orderHeader: header, record: item }) => {
      orderHeader.value = header;
      record.value = item;

      //基础卡信息
      const { memberCode } = orderHeader.value;
      const { goodsExtendedCode: cardNo } = record.value;

      const cardNoList = cardNo?.split(',').filter((d) => d);
      const cardTimesPack = [],
        cardMoneyPack = [];

      await Promise.all(
        cardNoList?.map(async (d) => {
          const { userCardPack } = await POST('/card/getUserOneCardBenefitsInfo', {
            pageFlag: false,
            memberCode,
            cardNo: d,
          });

          if (userCardPack.typeCode === '101') {
            cardMoneyPack.push(userCardPack);
          } else {
            cardTimesPack.push(userCardPack);
          }
        }),
      );

      state.cardTimesPack = cardTimesPack?.map((o) => ({ cardType: '200', ...o })) || [];
      state.cardMoneyPack = cardMoneyPack?.map((o) => ({ cardType: '100', ...o })) || [];
      state.cardEffectivePack = getCardList([1, 2]);
      state.cardInvalidPack = getCardList([3]);
      state.version = Math.random();
    },
  );

  function getCardList(statusList) {
    const result = [];

    result.push(...state.cardTimesPack.filter((o) => exist(o.status, statusList)));
    result.push(...state.cardMoneyPack.filter((o) => exist(o.status, statusList)));

    return result;
  }

  function onSelect(item) {
    refundDrawer3(true, { orderHeader: orderHeader.value, record: record.value, cardItem: item });
    closeModal();
  }
</script>

<style lang="less" scoped>
  .panel {
    padding: 8px 16px;
  }
</style>
